var db = require('../config/mongo_database');
var secret = require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;

var tokenManager = require('../config/token_manager');
var logger = require('../config/log4js').logger('access');
var balance = require('../route/balance');
var property = require('../route/property');


// 根据活动查询参与用户
exports.actlist = function(req, res){
	var actid   =  req.body.actid  || ''; 

	db.useractModel.find({actid:actid}, function(err, list){
		res.json(list);
	})
}



// APP活动列表
exports.list = function(req, res){
	var userid = tokenManager.getUserId(req);

	db.useractModel.find({userid:userid}, function(err, list){
		res.json(list);
	})
}

/**
	参与活动
	1. 首先判读活动是否结束（人数根据人数来判断，时间根据时间来判断）
	
	2. 根据活动类型判断用户是否账户有余额

	3. 余额充足进行扣款，余额不足进行提示
	额外
	如果人数并发太多，可以暂时把请求人数都缓存到redis队列，读取队列长度，超过则截取

**/
exports.vote = function(req, res){
	var actid   =  req.body.actid  || ''; 
	var user    =  tokenManager.getUser(req);

	db.activityModel.findOne({_id: actid}, function(err, active){
		if(err){
			logger.error("未查询到db.activityModel.findOne({_id: actid}", actid)
			res.json({status:404, msg:'活动不存在'});
		}

		if(active.type=='1'){
			actOne(active, user, res)
		}else if(active.type=='2'){
			actTwo(active, user, res)
		}else{
			res.json({status:404, msg:'活动不存在'});
		}
		
	})
}

function actOne(active, user, res){
	db.useractModel.count({actid: active._id}, function(err, count){
		if(count < active.member){
			withhold(user, active, res)
		}
		return res.json({status:405, msg:'活动结束'});
	})
}

function actTwo(active, user, res){
	var current = moment(new Date()).format("YYYYMMDDHHmm")+''
	if(current > active.start && current < active.end){
		withhold(user, active, res)
	}
	return res.json({status:405, msg:'活动结束'});
}


// 生成充值订单
// exports.recharge = function(req, res){
// 	var userid = tokenManager.getUserId(req);
// 	var detail = {}
// 	detail.type   =  req.body.type  || null; // 币种类别
// 	detail.addr   =  req.body.addr  || ''; // 发送地址
// 	detail.asset  =  req.body.asset || ''; // 金额

// 	var property = new db.propertyModel();
// 	property.detail    = detail 
// 	property.content   = '账户充币'
     
//     property.save(function(err) {
//     	if(err)
//     		logger.error('property.save', userid, detail, content)
// 	});
// }

// 获取后台订单列表
exports.backlist = function(req, res) {
	var trade = req.body.trade || '';
	var type = req.body.type || null;
	var pages = req.body.pages || 0;
	
	var where = {status:'1'};
	if(trade!='') where.trade = trade;
	if(type!='')  where.type  = type;

	db.propertyModel.count(where, function(err, count){
		db.propertyModel
		.where(where)
		.skip(pages*12)
		.limit(12)
		.sort({ updated : -1 })
		.exec(function(err, list){
			res.json({count:count, list:list});
		})
	})
};


// 更新充值记录
exports.charge = function(req, res){
	var id = req.body._id

	db.propertyModel.findOne({_id:id, status:'1', trade:'1'}, function(err, order){
		if(err) {
			logger.error("未查询到该笔订单[propertyModel:{_id:id, status:'1', trade:'1'}]", id)
			return res.sendStatus(500);
		}
		else{
			chargeProperty(order)
			return res.sendStatus(200);
		}
	})
}

/**
   1. 确认到账后，进行更新
   2. 首先更新订单，状态改为交易成功
   3. 目标客户对应钱包进行充值
   4. 新增交易记录到对账单
   风险点：如扣款和增款同时发生如何避免？ 另外还有获奖金额？

   人工操作：优先处理此人扣款操作，再处理增款操作

**/
function chargeProperty(order){
	db.propertyModel.update({_id:order.id, status:'1', trade:'1'}, {$set:{trade:'2', updated:new Date()}}, function(err){
		if(err) 
			logger.error("更新失败db.propertyModel.update({_id:order.id, status:'1', trade:'1'}, {$set:{trade:'2'}}", id)
		else
			db.userModel.findOne({_id: order.userid}, function(err, user){
				user.wallet[order.detail.type].asset = user.wallet[order.detail.type].asset + order.detail.asset;
				db.userModel.update({_id: order.userid}, {$set:{wallet: user.wallet, updated:new Date()}}, function(err){
					if(err)
						logger.error("更新失败db.userModel.update({_id: order.userid}, {$set:{wallet: user.wallet}}", user.wallet)
					else
						balance.addBalance(order.userid, order.detail.type, order.detail.asset)
				})
			})
	})
}

//  扣款
function withhold(user, active, res){
	db.userModel.findOne({_id:user.id}, function(err, u){
		var type = Number(active.btype)
		if(u.wallet[type].asset >= active.price){
			u.wallet[type].asset = u.wallet[type].asset - active.price
			db.userModel.update({_id:user.id}, {$set:{wallet:u.wallet}}, function(err){
				if(err){
					return res.json({status:502, msg:'扣款失败'});
				}else{
					// 更新对账单记录
					balance.addBalance(user.id, active.btype, (-1)*active.price)
					// 更新我的账单
					property.addProperty({
						userid:  user.id,
						type:    '1',
						btype:   active.btype
						content: active.name+'活动扣款',
						pay:     (-1)*active.price,
						trade:   '2',
						detail:  {nick:user.nick, username:user.username, actid:active._id, actname:active.name}
					})

					useract            = new db.useractModel()
					useract.userid     = user.id
					useract.actid      = active._id
					useract.payAmount  = active.price
					useract.proof      = ""          //中奖号码
					useract.type       = active.btype
					useract.info       = {name:active.name, nick:user.nick}
					useract.save(function(err) {
				    	if(err){
				    		logger.error('useract.save', user.id, active._id)
				    		return res.json({status:503, msg:'系统错误,请联系客服'});
				    	}else{
				    		return res.json({status:200, msg:'参与成功,请到我的活动查看'});
				    	}
					});
				}
			})
		}else{
			return res.json({status:402, msg:'余额不足'});
		}
	})
}